<?php 
/**
 * @description : get the show contents of video viewing.
 * @class-name : ModuleResultOfVideo().
 * @author : stephen.mo
 * @date : 2010-04-21
 */

class ModuleResultOfVideo extends CmsCustomModule {
    
    //set the output page header.
    private function setHeadString($condition=null,$sort_by=null,$rand_code) {
        $date_list = null;
        $current_time = date('Y-m-d H:i:s');
        $gender_list = ' NONE ';
        $age_group_list = ' NONE ';
        $region_country_list = ' NONE ';
        $subscription_plan = 'Free';
        $category_list = ' NONE ';
        
        if (!empty($condition) && is_array($condition)) {

            //date time.
            if (isset($condition['play_time']['start_date']) && isset($condition['play_time']['end_date'])) {
                $date_list = '<strong>By Date: </strong>&nbsp; <b>From</b> '.$condition['play_time']['start_date'].' <b>To</b> '.$condition['play_time']['end_date'];
            }
            else {
                $date_list = '<b>By Month: </b>&nbsp;'.$condition['play_time']['year'].' - '.$condition['play_time']['month'];
            }
            
            //gender & age.
            if (!empty($condition['gender'])) {
                $gender_list = (count($condition['gender'])==0) ? 'NONE' : ((count($condition['gender'])==2) ? 'ALL' : (($condition['gender'][0]=='M') ? 'Male' : 'Female'));
            }

            $age_group_mapping = AC::getInstance()->getConfigSetting(AC::$age_list);
            if (!empty($condition['age_group'])) {
                foreach($condition['age_group'] as $key=>$val) {
                    $tmp_ages[]= $age_group_mapping[$val];
                }
                $age_group_list = implode(', ',$tmp_ages);                
            }
            
            //region & country
            if (!empty($condition['country_code'])) {
                $country_arr = $condition['country_code'];
                $region_country_list = AC::getInstance()->getCountryListToHeader($country_arr);
            }

            //categorys
            if (!empty($condition['category_path'])) {
                $category_list = implode(', ',$condition['category_path']);
            }

            //subscription plan
            if ($condition['content_type']==2) {
                $plan_array = AC::getInstance()->getConfigSetting(AC::$video_plan_package);
                $tmp_plan = array();
                foreach($plan_array as $key=>$val) {
                    if ($key==0 && strtoupper($val)=='ALL') continue;
                    $tmp_plan[] = $key;
                }

                $tmp_plan_list = array();
		if (is_array($condition['package_id'])) {
	                foreach($condition['package_id'] as $key=>$val) {
        	            $tmp_plan_list[] = (isset($plan_array[$val])) ? $plan_array[$val] : null ;
                	}
		}

                $subscription_plan = (count($tmp_plan)==count($tmp_plan_list)) ? 'Premium (ALL)' : 'Premium ( '.implode(', ',$tmp_plan_list).' )';
            }
        }

        $condition_list = '<br/>'.
                          '<div>'.$date_list.'</div>'.
                          '<div><b>Top: </b>&nbsp;'.$condition['top_limit'].'</div>'.
			              '<div><b>Video Category: </b>&nbsp;'.$category_list.'</div>'.
                          '<div><b>Subscription Plan: </b>&nbsp;'.$subscription_plan.'</div>'.
			              '<div><b>Gender: </b>&nbsp;'.$gender_list.'</div>'.
			              '<div><b>Age Group: </b>&nbsp;'.$age_group_list.'</div>'.
			              '<table class="nob">'.
                          '<tr>'.
                          ' <td valign="top" width="110">'.
                          '     <b class="tit">Region/Country: </b>&nbsp;</td>'.
                          ' <td valign="top">'.$region_country_list.'</td>'.
                          '</tr>'.
                          '</table>'.
                          '<div><b>Sort By: </b>&nbsp;'.ucwords($sort_by).'</div>';
        //export tag.
        $export_tag =  'Export to '.AC::exportHtmlControl($rand_code,AC::EXPORT_FILE_PREFIX_NAME_VIDEO_VIEWING)
                                   .AC::exportPdfControl($rand_code,AC::EXPORT_FILE_PREFIX_NAME_VIDEO_VIEWING)
                                   .AC::exportCvsControl($rand_code,AC::EXPORT_FILE_PREFIX_NAME_VIDEO_VIEWING);

        $head_string = '<div class="hd">'.
                       '    <div class="utility">'.
                       '        <a href="#" class="print">Print</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$export_tag.
                       '    </div>'.
                       '    <hr>'.
                       '    <h1>'.$this->title.'</h1>'.
                       '    <div class="ui-helper-clearfix">'.
                       '        <div class="time">'.$current_time.'</div>'.
                       '        <ul>'.$condition_list.'</ul>'.
                       '    </div>'.
                       '</div>';

        $head_string_exprot = '<div class="hd">'.
                                '    <div class="utility">'.
                                '        <a href="#" class="print">Print</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.
                                '    </div>'.
                                '    <hr>'.
                                '    <h1>'.$this->title.'</h1>'.
                                '    <div class="ui-helper-clearfix">'.
                                '        <div class="time">'.$current_time.'</div>'.
                                '        <ul>'.$condition_list.'</ul>'.
                                '    </div>'.
                                '</div>';
        return array('view'=>$head_string,'export'=>$head_string_exprot);
    }
    
    //set the body's paragraph title
    private function setParagraphTitle($title) {
        $body = '<tr>'.
                '   <td colspan="5" class="tit">'.
                '       <div align="center"><strong>'.$title.'</strong></div>'.
                '   </td>'.
                '</tr>';
        return $body;
    }

    //set the body's public rows
    private function setPubRowsOfBody($category,$sort_by) {
        $body = '<tr>'.
                '   <td width="225"><b>Category:'.ucwords($category).'</b></td>'.
                '   <td width="165">&nbsp;</td>'.
                '   <td width="60">&nbsp;</td>'.
                '   <td width="95">&nbsp;</td>'.
                '   <td width="95">&nbsp;</td>'.
                '</tr>'.
                '<tr>'.
                '   <td bgcolor="#CCCCCC"><b>Video Title - Sort By ( '.ucwords($sort_by).' )</b></td>'.
                '   <td bgcolor="#CCCCCC" ><b>Group By</b></td>'.
                '   <td bgcolor="#CCCCCC" align="right"><b>Frequency</b></td>'.
                '   <td bgcolor="#CCCCCC" align="right"><b>Duration</b></td>'.
                '   <td bgcolor="#CCCCCC" align="right"><b>Average</b></td>'.
                '</tr>';
        return $body;
    }
    
    //set the rows when condition is none.
    private function setPubRowsOfBodyByNone($category,$sort_by,$flag=true) {
        $body = null;
        if ($flag) {
            $body = '<tr>'.
                    '   <td width="225"><b>Category：'.ucwords($category).'</b></td>'.
                    '   <td width="165">&nbsp;</td>'.
                    '   <td width="60">&nbsp;</td>'.
                    '   <td width="95">&nbsp;</td>'.
                    '   <td width="95">&nbsp;</td>'.
                    '</tr>';
        }

        $body.= '<tr>'.
                '   <td bgcolor="#CCCCCC"><b>Video Title - Sort By ( '.ucwords($sort_by).' )</b></td>'.
                '   <td bgcolor="#CCCCCC">&nbsp;</td>'.
                '   <td bgcolor="#CCCCCC" align="right"><b>Frequency</b></td>'.
                '   <td bgcolor="#CCCCCC" align="right"><b>Duration</b></td>'.
                '   <td bgcolor="#CCCCCC" align="right"><b>Average</b></td>'.
                '</tr>';
        return $body;
    }

    //set the body's sub title.
    private function setSubTitleOfBody($num,$title) {
        $body = '<tr>'.
                '   <td colspan="5"><b>Top'.$num.': '.$title.'</b></td>'.
                '</tr>';
        return $body;
    }
    
    //set the sub title when condition is none.
    private function setSubTitleOfBodyByNone($num,$title,$frequency,$duration,$avg) {
        $frequency = number_format($frequency);
        $duration = timeFormat::getinstance()->hourMinSec($duration);
        $avg = timeFormat::getinstance()->hourMinSec($avg);
        $body = '<tr>'.
                '   <td>Top'.$num.': '.$title.'</td>'.
                '   <td>&nbsp;</td>'.
                '   <td align="right">'.$frequency.'</td>'.
                '   <td align="right">'.$duration.'</td>'.
                '   <td align="right">'.$avg.'</td>'.
                '</tr>';
        return $body;
    }

    //set the start rowspan and line.
    private function setStartRowspanOfBody($rows,$aves_char) {
        $body = '<tr>'.$rows.
                '   <td><b>'.$aves_char.'</b></td>'.
                '   <td align="right"><b>{GENDER_TOTAL_F}</b></td>'.
                '   <td align="right"><b>{GENDER_TOTAL_D}</b></td>'.
                '   <td align="right"><b>{GENDER_AVG}</b></td>'.
                '</tr>';
        return $body;
    }

    //set the second line of body. one by one.
    private function setSecondLineOfBody($rowspan,$aves_text,$frequency,$duration,$avg) {
        $frequency = number_format($frequency);
        $duration = timeFormat::getinstance()->hourMinSec($duration);
        $avg = timeFormat::getinstance()->hourMinSec($avg);
        $body = '<tr>'.$rowspan.
                '   <td>&nbsp;&nbsp;&nbsp;&nbsp;<I>'.$aves_text.'</I></td>'.
                '   <td align="right"><I>'.$frequency.'</I></td>'.
                '   <td align="right"><I>'.$duration.'</I></td>'.
                '   <td align="right"><I>'.$avg.'</I></td>'.
                '</tr>';
        return $body;
    }
    
    //set the second line of body for country & region
    private function setSecondLineOfBodyForCountry($section_text) {
        $body = '<tr>'.
                '   <td>&nbsp;&nbsp;&nbsp;&nbsp;<b><I>'.$section_text.'</I></b></td>'.
                '   <td align="right"><b><I>{SECTION_TOTAL_F}</I></b></td>'.
                '   <td align="right"><b><I>{SECTION_TOTAL_D}</I></b></td>'.
                '   <td align="right"><b><I>{SECTION_AVG}</I></b></td>'.
                '</tr>';
        return $body;
    }

    //set the third line of body for country * region
    private function setThirdLineOfBodyForCountry($country_text,$frequency,$duration,$avg) {
        $frequency = number_format($frequency);
        $duration = timeFormat::getinstance()->hourMinSec($duration);
        $avg = timeFormat::getinstance()->hourMinSec($avg);
        $body = '<tr>'.
                '   <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$country_text.'</td>'.
                '   <td align="right">'.$frequency.'</td>'.
                '   <td align="right">'.$duration.'</td>'.
                '   <td align="right">'.$avg.'</td>'.
                '</tr>';
        return $body;
    }

    //set the total list of the end line.
    private function setTotalOfEndList($frequency,$duration) {
        $avg = (($frequency!=0) ? round($duration/$frequency) : 0);
        $frequency = number_format($frequency);
        $duration = timeFormat::getinstance()->hourMinSec($duration);
        $avg = timeFormat::getinstance()->hourMinSec($avg);
        $body = '<tr>'.
                '   <td><b>Total</b></td>'.
                '   <td align="right"><b>'.$frequency.'</b></td>'.
                '   <td align="right"><b>'.$duration.'</b></td>'.
                '   <td align="right"><b>'.$avg.'</b></td>'.
                '</tr>';
        return $body;
    }

    //set the blank line.
    static private function setBlanLineAtEnd() {
        $body = '<tr>'.
                '   <td width="194"></td>'.
                '   <td width="195">&nbsp;</td>'.
                '   <td width="117">&nbsp;</td>'.
                '   <td width="95">&nbsp;</td>'.
                '   <td width="49">&nbsp;</td>'.
                '</tr>';
        return $body;
    }
    
    //set a blank line with message.
    private function setBlankLineWithMessage($message) {
        $body = '<tr height="60"><td colspan="5" align="center">'.$message.'</td></tr>';
        return $body;
    }

    //out put the body string.
    private function getOutPutBody($head_string,$body_string) {
        $output ='<div id="result" class="video_result">'.$head_string.
                 '  <div class="bd">'.
                 '      <table border="0" cellpadding="0" cellspacing="0">'.
                        $body_string.
                 '      </table>'.
                 '  </div>'.
                 '</div>';
        return $output;
    }

    //get the all layer num of country.
    public function countArrayLayers($array) {
        $num = 0;
        foreach($array as $k=>$v) {
            $num++;
            foreach($v as $k1=>$v1) {
                //if(strtoupper($k1)!='ASIA' && strtoupper($k1)!='EUROPE' && strtoupper($k1)!='OCEANIA') {
                if(strtoupper($k1)!=strtoupper($k)) {
                    $num++;
                }
                $num+=count($v1);
            }
        }
        return $num;
    }

    //set the main body list.
    private function setMainBodyList($datas,$aves_char,$aves_list,$sort_by,$age_group_array) {

        $body_list = null;
        $count_aves_char = (empty($aves_char)) ? 1 : count($aves_char);
        $count_aves_list = count($aves_list);
        $count_unit = (empty($aves_char)) ? 0 : count($aves_char);
        $video_info = (isset($datas['video_info'])) ? $datas['video_info'] : null;
        $data = (isset($datas['data'])) ? $datas['data'] : $datas;

        $rows = (empty($aves_char) && !empty($aves_list)) ? $count_aves_list : $count_aves_list * $count_aves_char + $count_unit;
        $rows_all = ($rows == 1) ? $rows : $rows+1;
        $array_count = count($age_group_array);
        

        foreach($data as $key=>$value) {
            $body_list.= $this->setPubRowsOfBody($key,$sort_by);
            $n = 1;

            foreach($value as $key2=>$value2) {
                $video_title = (isset($video_info[$key2])) ? $video_info[$key2] : '該video不存在 ('.$key2.')';
                $body_list.= $this->setSubTitleOfBody($n,$video_title);//$value2['attr']['video_title']); 
                $p=0;
                $tmp_flag = false;
                $line_total_frequency = 0;
                $line_total_duration = 0;

                foreach($value2['list'] as $key3=>$value3) {
                    $line_total_gender_f = 0;
                    $line_total_gender_d = 0;
                    
                    if (!is_numeric($key3)) {

                        if ($key3=='Premium') {
                            $tmp_flag = true;
                            $rows = $rows_all-1;
                        }
                        else {
                            $rows = $rows_all;
                        }

                        $key3 = ($key3=='Premium') ? ((count($aves_list)==$array_count) ? $key3.' (All Subscription Plans) ' : $key3.' (Some Subscription Plans) ') : $key3;
                        $rows_span_ = null;
                        $rows_span = ($p<=0) ? '<td rowspan="'.$rows.'">&nbsp;</td>' : null;
                        $body_list .= $this->setStartRowspanOfBody($rows_span,$key3);
                        $p++;
                    }
                   
                    //logic for have age group.
                    foreach((array)$aves_list as $key4=>$value4) {
                        $rows_span_ = ($p<=0) ? '<td rowspan="'.$rows_all.'">&nbsp;</td>' : null;
                        $group_text = (isset($age_group_array[$value4])) ? $age_group_array[$value4] : null;
                        $group_frequency = (isset($value3[$value4]['frequency'])) ? $value3[$value4]['frequency'] : 0;
                        $group_duration = (isset($value3[$value4]['duration'])) ? $value3[$value4]['duration'] : 0;
                        $group_avg = ($group_frequency!=0) ? round($group_duration/$group_frequency) : 0;
                        $body_list.= $this->setSecondLineOfBody($rows_span_,$group_text,$group_frequency,$group_duration,$group_avg);
                        $line_total_frequency += $group_frequency;
                        $line_total_duration += $group_duration;
                        $line_total_gender_f += $group_frequency;
                        $line_total_gender_d += $group_duration;
                        $p++;
                    }

                    //logic for havn't age group list.
                    if (empty($aves_list) && !empty($aves_char)) {
                        foreach($value3 as $key4=>$value4) {
                            $group_frequency = (isset($value4['frequency'])) ? $value4['frequency'] : 0;
                            $group_duration = (isset($value4['duration'])) ? $value4['duration'] : 0;
                            $group_avg = ($group_frequency!=0) ? round($group_duration/$group_frequency) : 0;
                            $line_total_gender_f += $group_frequency;
                            $line_total_gender_d += $group_duration;
                            $line_total_frequency += $group_frequency;
                            $line_total_duration += $group_duration;
                        }
                    }
                    
                    $line_total_gender_avg = ($line_total_gender_f==0) ? 0 : round($line_total_gender_d/$line_total_gender_f);
                    $frequency_s = number_format($line_total_gender_f);
                    $duration_s = timeFormat::getinstance()->hourMinSec($line_total_gender_d);
                    $avg_s = timeFormat::getinstance()->hourMinSec($line_total_gender_avg);
                    $body_list = str_replace('{GENDER_TOTAL_F}',$frequency_s,$body_list);
                    $body_list = str_replace('{GENDER_TOTAL_D}',$duration_s,$body_list);
                    $body_list = str_replace('{GENDER_AVG}',$avg_s,$body_list);
                    $p++;   
                }
                

                $body_list .= ($rows==1 || $tmp_flag) ? null : $this->setTotalOfEndList($line_total_frequency,$line_total_duration);
                $n++;
            }

            //set a blank line
            //$body_list .= self::setBlanLineAtEnd();
        }        
        
        return $body_list;
    }
  
    //set the special body list.
    private function setMainBodyList_($data,$first_layer,$layer_data,$sort_by) {
        $body_list = null;
        $data = (isset($data['data'])) ? $data['data'] : $data;
        $video_info = (isset($datas['video_info'])) ? $datas['video_info'] : null;
        $layer_rows = $this->countArrayLayers($layer_data);
        $layer_rows = (count($layer_data)>1) ? $layer_rows+1 : $layer_rows;

        foreach($data as $key=>$value) {
            $body_list.= $this->setPubRowsOfBody($key,$sort_by);
            $n = 1;
            foreach($value as $key2=>$value2) {
                $video_title = (isset($video_info[$key2])) ? $video_info[$key2] : '該video不存在 ('.$key2.')';
                $body_list.= $this->setSubTitleOfBody($n,$video_title);//$value2['attr']['video_title']); 
                $line_total_f = 0;
                $line_total_d = 0;
                $line_total_frequency = 0;
                $line_total_duration = 0;
                //stat
                $p=0;
                $tmp_data = $value2['list'];
                foreach($layer_data as $key3=>$value3) {
                    $key3_ = null;
                    $stat_line_f = 0;
                    $stat_line_d = 0;
                    $rows = $layer_rows;
                    $rows_span = ($p<=0) ? '<td rowspan="'.$rows.'">&nbsp;</td>' : null;

                    //if(strtoupper($key3)=='ASIA' || strtoupper($key3)=='EUROPE' || strtoupper($key3)=='OCEANIA') {
                    //if(strtoupper($key3)==strtoupper($key2)) {
                        $sub_country_total_ = self::getAllCountryList($key3,$key3);
                        $key3_ = (count($value3[$key3])<$sub_country_total_) ? $key3.' (Some Countries) ': $key3.' (All Countries) ';
                    //}
                    $key3_text = (!empty($key3_)) ? $key3_ : $key3;
                    $body_list .= $this->setStartRowspanOfBody($rows_span,$key3_text);
                    
                    //section
                    foreach($value3 as $key4=>$value4) {
                        $section_line_f = 0;
                        $section_line_d = 0;
                        //if (strtoupper($key4)!='ASIA' && strtoupper($key4)!='EUROPE' && strtoupper($key4)!='OCEANIA') {
                        if (strtoupper($key4)!=strtoupper($key3)) {
                            $sub_country_total = self::getAllCountryList($key3,$key4);
                            $key4_text = (count($value4)<$sub_country_total) ? $key4.' (Some Countries) ' : $key4.' (All Countries) ';
                            $body_list .= $this->setSecondLineOfBodyForCountry($key4_text);
                        }

                        //country
                        foreach($value4 as $key5=>$value5) {
                            $country_frequency = (isset($tmp_data[$key3][$key4][$key5]['frequency'])) ? $tmp_data[$key3][$key4][$key5]['frequency'] : 0;
                            $country_duration = (isset($tmp_data[$key3][$key4][$key5]['duration'])) ? $tmp_data[$key3][$key4][$key5]['duration'] : 0;
                            $country_avg = ($country_frequency==0) ? 0 : round($country_duration/$country_frequency);
                            $body_list .= $this->setThirdLineOfBodyForCountry($value5.' ('.$key5.')',$country_frequency,$country_duration,$country_avg);
                            $section_line_f += $country_frequency;
                            $section_line_d += $country_duration;
                            $line_total_frequency += $country_frequency;
                            $line_total_duration += $country_duration;
                        }

                        $stat_line_f += $section_line_f;
                        $stat_line_d += $section_line_d;
                        //replace
                        if (strtoupper($key4)!='ASIA' && strtoupper($key4)!='EUROPE' && strtoupper($key4)!='OCEANIA') {
                            $section_line_avg = ($section_line_f==0) ? 0 : round($section_line_d/$section_line_f);
                            $time_f = number_format($section_line_f);
                            $time_d = timeFormat::getinstance()->hourMinSec($section_line_d);
                            $time_a = timeFormat::getinstance()->hourMinSec($section_line_avg);

                            $body_list = str_replace('{SECTION_TOTAL_F}',$time_f,$body_list);
                            $body_list = str_replace('{SECTION_TOTAL_D}',$time_d,$body_list);
                            $body_list = str_replace('{SECTION_AVG}',$time_a,$body_list);
                        }

                    }

                    $line_total_f += $stat_line_f;
                    $line_total_d += $stat_line_d;
                    //echo $key3."line_total:".$line_total_f."----".$line_total_d."<br>";
                    $stat_line_avg = ($section_line_f==0) ? 0 : round($stat_line_d/$stat_line_f);
                    //replace
                    $time_f = number_format($line_total_f);
                    $time_d = timeFormat::getinstance()->hourMinSec($line_total_d);
                    $time_a = timeFormat::getinstance()->hourMinSec($stat_line_avg);

                    $body_list = str_replace('{GENDER_TOTAL_F}',$time_f,$body_list);
                    $body_list = str_replace('{GENDER_TOTAL_D}',$time_d,$body_list);
                    $body_list = str_replace('{GENDER_AVG}',$time_a,$body_list);
                    $line_total_f = 0;
                    $line_total_d = 0;
                    $p++;
                }

                $body_list .= (count($layer_data)>1) ? $this->setTotalOfEndList($line_total_frequency,$line_total_duration) : null;
                $n++;
            }

            //set a blank line
            $body_list .= self::setBlanLineAtEnd();
        }
        return $body_list;
    }

    //set the body list with none params
    private function setMainBodyListByNone($data,$sort_by,$flag) {
        $body_list = null;
        $video_info = $data['video_info'];
        $tmp_data = $data['data'];
        if (isset($data)) unset($data);
        foreach($tmp_data as $key=>$value) {
            //$body_list .= (!$flag) ? null : $this->setPubRowsOfBodyByNone($key,$sort_by,$flag);
            $body_list .= $this->setPubRowsOfBodyByNone($key,$sort_by,$flag);
            $n = 1;
            foreach($value as $key2=>$value2) {
                $video_id = $key2;
                $video_title = (isset($video_info[$video_id])) ? $video_info[$video_id] : '該video不存在 ('.$video_id.')';
                $line_attr_f = $value2['attr']['frequency'];
                $line_attr_d = $value2['attr']['duration'];
                $line_attr_avg = ($line_attr_f==0) ? 0 : round($line_attr_d/$line_attr_f);
                $body_list .= $this->setSubTitleOfBodyByNone($n,$video_title,$line_attr_f,$line_attr_d,$line_attr_avg);
                $n++;
            }

            //$body_list .= self::setBlanLineAtEnd();
        }

        return $body_list;
    }

    private function getVideoTitleByVideoIds($video_ids) {
        $video_info = array();
        $result = array();
        $client = new PMSWebServiceClient();
        $video_info = $client->getVideoInformationByVideoIds($video_ids);
        if (!empty($video_info) && is_array($video_info)) {
            foreach($video_info as $value) {
                $video_id = $value['id'];
                $video_title = $value['title'];
                $result[$video_id] = $video_title;
            }
        }
        return $result;
    }


    //set the no data on list.
    private function setMainBodyListHaveNone() {
        return $this->setBlankLineWithMessage(ErrorMessage::HAVE_NO_DATA);
    }

    //get the page search filter condition.
    private function getPageCondition($params) {
        //Array ( [action] => video_result [month] => 01 [year] => 2010 [startdate] => 2010-04-22 [enddate] => 2010-04-23 [age] => 4,5,6 [category] => variety,lifestyle [gender] => 2 [plan] => premium [package] => 2,4 [country] => China, [sortby] => duration ) 
        $age_group = array();
        if (!empty($params['age'])) {
            $tmp_age_group = explode(',',$params['age']);
            foreach($tmp_age_group as $key=>$val) {
                if (intval($val)==-1) {
                    $age_group = array();
                    $tmp_arr = AC::getInstance()->getConfigSetting(AC::$age_list);
                    foreach($tmp_arr as $k=>$v) {
                        if ($k=='0' || $k=='-1') continue;
                        $age_group[] = $k;
                    }
                    break;
                }
                if (intval($val)==0) continue;
                $age_group[] = intval($val);
            }
        }

        $date = array();
        if (!empty($params['startdate']) && !empty($params['enddate'])) {
            $date['start_date'] = $params['startdate'];
            $date['end_date'] = $params['enddate'];
            if ($params['enddate']<$params['startdate']) $date['end_date'] = date('Y-m-d');
        }

        $month = array();
        if (!empty($params['month'])) {
            $month['year'] = (!empty($params['year'])) ? $params['year'] : date('Y');
            $month['month'] = $params['month'];
        }
        $play_time = ($params['dateby']=='month') ? $month : $date;

        $category = array();
        if (!empty($params['category'])) {
            $tmp_category = explode(',',$params['category']);
            $category = array();
            foreach($tmp_category as $key=>$val) {
                if ($val=='all') {
                    $category = array();
                    $tmp_arr = AC::getInstance()->getConfigSetting(AC::$category_list);
                    foreach($tmp_arr as $k=>$v) {
                        if ($k=='0' || $k=='all') continue;
                        $category[]=$k;
                    }
                    break;
                }
                $category[]=ucwords($val);
            }
        }
        
        $gender = array();
        if (!empty($params['gender'])) {
            $tmp_gender = array('2'=>'M','3'=>'F');
            if ($params['gender']==1) {
                $gender = array('M','F');
            }
            else {
                $gender[] = $tmp_gender[$params['gender']];
            }
        }
        
        $plan = array();
        if (!empty($params['plan'])) {
            $tmp_plan = array('free'=>1,'premium'=>2);
            $tmp_package = AC::getInstance()->getConfigSetting(AC::$video_plan_package);
            $tmp_package_ = array_keys($tmp_package);
	        $tmp_package_key = array();
            foreach($tmp_package_ as $k=>$v) {
                if ($k==0) continue;
                $tmp_package_key[] = $v;
            }

            $plan['content_type'] = $tmp_plan[strtolower($params['plan'])];
            $plan['package_id'] = null;
            if ($plan['content_type']==2) {
                $tmp_package_ids = explode(',',$params['package']);
                foreach($tmp_package_ids as $key=>$val) {
                    if ($val == 0) {
                        $plan['package_id'] = $tmp_package_key;
                        break;
                    }
                    else {
                        $plan['package_id'][] = $val;
                    }
                }
            }
        }

        $country = array();
        if (!empty($params['country_code'])) {
            $country = (!empty($params['country_code'])) ? json_decode($params['country_code'],true) : array();
        }

        $top_limit = AC::$top_size_default_value;
        if (!empty($params['top_size'])) {
            $top_limit = intval($params['top_size']);
        }

        $sort = $params['sortby'];

        return array('condition'=>array('age_group'=>$age_group,
                                         'play_time'=>$play_time,
                                         'category_path'=>$category,
                                         'gender'=>$gender,
                                         'content_type'=>$plan['content_type'],
                                         'package_id'=>$plan['package_id'],
                                         'country_code'=>$country,
                                         'top_limit'=>$top_limit,
                                    ),
                     'sort'=>$sort,
                );
    }
    
    //get the country list for area.
    protected function getCountryList($area) {
        $result = array();
        $result = getStatsClass::getInstance()->getStatsByKey($area);
        return $result;
    }
    
    //get the country count by stat & section.
    static public function getAllCountryList($stat,$section) {
        $data = array();
        $data = getStatsClass::getInstance()->getCountryByRegionAndSub($stat,$section);
        return count($data);
    }

    //get the table name.
    private function getDateCondition($play_time,$table_alias) {
        $table_name = array();
        $date_condition = '';
        if (!empty($play_time['start_date']) && !empty($play_time['end_date'])) {
            $date_condition .= ' AND (SUBSTRING('.$table_alias.'.play_time,1,10)>="'.$play_time['start_date'].'" AND SUBSTRING('.$table_alias.'.play_time,1,10)<="'.$play_time['end_date'].'") ';
            $start_ = date('Y',strtotime($play_time['start_date']));
            $end_ = date('Y',strtotime($play_time['end_date']));
            for($i=$start_;$i<=$end_;$i++) {
                $table_name['year'][] = $i;
                $table_name['month'] = 0;
            }
        }
        elseif(!empty($play_time['year']) && !empty($play_time['month'])) {
            $date_condition .= ' AND (SUBSTRING('.$table_alias.'.play_time,1,7)="'.$play_time['year'].'-'.$play_time['month'].'") ';
            $table_name['year'] = $play_time['year'];
            $table_name['month'] = $play_time['month'];
        }

        return array('table_name'=>$table_name,'condition'=>$date_condition);
    }
    
    //Optimization
    private function getDataConditionOptimization($play_time) {
        $date_condition = null;
        if (!empty($play_time['start_date']) && !empty($play_time['end_date'])) {
            $date_condition = ' AND (day_time >="'.$play_time['start_date'].'" AND day_time<="'.$play_time['end_date'].'") '; 
        }
        elseif(!empty($play_time['year']) && !empty($play_time['month'])) {
            $date_condition = ' AND (SUBSTRING(day_time,1,7)="'.$play_time['year'].'-'.$play_time['month'].'") ';
        }
        return array('condition'=>$date_condition);
    }
    

    //get the data for Gender & Age
    private function getGenderAgeGroupList($category_path,$play_time,$age_group,$gender,$content_type,$country_code,$package_ids,$sort_by) {
        $result = array();
        $categories_path = array();
        $countries_code = array();
        $tmp_date_arr = $this->getDataConditionOptimization($play_time);
        $condition = $tmp_date_arr['condition'];
        if(!empty($category_path)) {
            foreach($category_path as $category) {
                $categories_path[] = strtolower($category);
            }
        }
        if (!empty($country_code)) {
            foreach($country_code as $area_country) {
                foreach($area_country as $country) {
                    foreach($country as $key=>$value) {
                        $countries_code[] = $key;
                    }
                }
            }
        }

        $obj = new ModelReportPages();
        $data = $obj->getGenderAgeGroupCountOptimization($condition,$categories_path,$age_group,$gender,$content_type,$package_ids,$countries_code,$sort_by);
        $video_ids = $data['video_ids'];
        $result['video_info'] = $this->getVideoTitleByVideoIds($video_ids);
        $result['data'] = $data['data'];
        return $result;
    }

    //get the data for subscription plan
    private function getSubscriptionPlanGroupList($category_path,$play_time,$package_ids,$content_type,$country_code,$sort_by) {
        $result = array();
        $categories_path = array();
        $countires_code = array();
        $age_group = array();
        $gender = array();
        $tmp_date_arr = $this->getDataConditionOptimization($play_time);
        $condition = $tmp_date_arr['condition'];
        if(!empty($category_path)) {
            foreach($category_path as $category) {
                $categories_path[] = strtolower($category);
            }
        }
        if (!empty($country_code)) {
            foreach($country_code as $area_country) {
                foreach($area_country as $country) {
                    foreach($country as $key=>$value) {
                        $countries_code[] = $key;
                    }
                }
            }
        }
        
        $obj = new ModelReportPages();
        $data = $obj->getSubscriptionPlanGroupCountOptimization($condition,$categories_path,$age_group,$gender,$content_type,$package_ids,$countires_code,$sort_by);
        $video_ids = $data['video_ids'];
        $result['video_info'] = $this->getVideoTitleByVideoIds($video_ids);
        $result['data'] = $data['data'];

        return $result;
    }

    
    //get the data of region countrys
    private function getRegionCountryGroupList($category_path,$play_time,$country_code,$content_type,$sort_by) {
        $result = array();
        return $result;
    }
    
    //get all the total summary
    private function getTotalSummaryOfReport($play_time,$category_path,$content_type,$country_code,$age_groups,$gender,$package_ids,$sort_by,$top_limit) {
        $data = array();
        $result = array();
        $countries_code = array();
        $categories_path = array();

        $tmp_date_arr = $this->getDataConditionOptimization($play_time);
        $date_condition = $tmp_date_arr['condition'];
        $condition = $date_condition;
        $content_type = $content_type;//($content_type==1) ? 0 : $content_type;
        if (!empty($country_code)) {
            foreach($country_code as $area_country) {
                foreach($area_country as $country) {
                    foreach($country as $key=>$value) {
                        $countries_code[] = $key;
                    }
                }
            }
        }

        if(!empty($category_path)) {
            foreach($category_path as $category) {
                $categories_path[] = strtolower($category);
            }
        }
        

        $other_condition = array('category_path'=>$categories_path,'content_type'=>$content_type,'countries_code'=>$countries_code,'age_groups'=>$age_groups,'genders'=>$gender,'pakcage_ids'=>$package_ids);
        //instance obj.
        $obj = new ModelReportPages();
        $data = $obj->getTopTenRecordsOptimization($condition,$other_condition,$sort_by,$top_limit);
        $video_ids = $data['video_ids'];
        $result['video_info'] = $this->getVideoTitleByVideoIds($video_ids);
        $result['data'] = $data['data'];
        if (isset($data)) unset($data);
        return $result;
    }

    //private get all group data.
    private function getAllGroupDataOptimization($categories_path,$play_time,$age_group,$gender,$content_type,$package_ids,$countries_code,$exist_group,$sort_by,$pegging_countries_code,$top_limit) {
        $data = array();
        //get the date condition string.
        $tmp_date_arr = $this->getDataConditionOptimization($play_time);
        $condition = $tmp_date_arr['condition'];
        //instance obj.
        $obj = new ModelReportPages();
        $data = $obj->getAllGroupDataOptimization($condition,$categories_path,$age_group,$gender,$content_type,$package_ids,$countries_code,$sort_by,$exist_group,$pegging_countries_code,$top_limit);
        return $data;        
    }


    //set the group data .
    private function setAllGroupBodyStringOptimization($conditions) {
        if (empty($conditions)) return ErrorMessage::HAVE_NO_PARAMERTERS;
        //define the array.
        $condition = array();
        $condition = $conditions['condition'];
        $sort_by = $conditions['sort'];
        $pegging_countries_code = array();
        $categories_path = array();
        $age_group_array = array();
        $countries_code = array();
        $category_path = array();
        $package_array = array();
        $country_code = array();
        $package_ids = array();
        $exist_group = array();
        $data = array();
        $output = null;

        //get country list.
        if (!empty($condition['country_code'])) {
            $country_arr = $condition['country_code'];
            $country_code = AC::getInstance()->getRegionCountryCondtion($country_arr);
        }

        if (!empty($condition['category_path'])) {
            $category_path = $condition['category_path'];
        }

        if ($condition['content_type']==2 && !empty($condition['package_id'])) {
            $package_ids = $condition['package_id'];
        }

        //Gender & Age Group
        if (!empty($condition['age_group']) || !empty($condition['gender'])) {
            $age_group_array_ = AC::getInstance()->getConfigSetting(AC::$age_list);
            foreach($age_group_array_ as $k=>$v) {
                if ($k<1) continue;
                $age_group_array[$k] = $v;
            }
            $exist_group[] = 'GenderAge';
        }
        
        //region & Country Group.
        if (isset($condition['country_code']) && !empty($condition['country_code'])) {
            $exist_group[] = 'RegionCountry';
        }

        //Subscription Plan Group.
        if ((!empty($condition['content_type']) || !empty($condition['package_id']))) {
            $package_array_ = AC::getInstance()->getConfigSetting(AC::$video_plan_package);
            foreach($package_array_ as $k=>$v) {
                if ($k==0 && $v=='ALL') continue;
                $package_array[$k] = $v;
            }
            $exist_group[] = 'SubscriptionPlan';
        }

        //category_path.
        if(!empty($category_path)) {
            foreach($category_path as $category) {
                $categories_path[] = strtolower($category);
            }
        }

        //country code list.all region's country
        if (!empty($country_code)) {
            foreach($country_code as $area_country) {
                foreach($area_country as $country) {
                    foreach($country as $key=>$value) {
                        $countries_code[] = $key;
                    }
                }
            }
        }

        //Pegging countries region
        if (!empty($country_code)) {
            foreach($country_code as $region=>$region_val) {
                foreach($region_val as $area=>$area_val) {
                    foreach($area_val as $key=>$value) {
                        $pegging_countries_code[$key] = array('Region'=>$region,'Area'=>$area);
                    }
                }
            }
        }
                
        //age    :$condition['category_path'],$condition['play_time'],$condition['age_group'],$condition['gender'],$condition['content_type'],$countries_code,$package_ids,$sort_by
        //plan   :$condition['category_path'],$condition['play_time'],$condition['package_id'],$condition['content_type'],$condition['country_code'],$sort_by
        //country:$condition['category_path'],$condition['play_time'],$tmp_country_code_list,$condition['content_type'],$sort_by
        $data = $this->getAllGroupDataOptimization($categories_path,$condition['play_time'],$condition['age_group'],$condition['gender'],$condition['content_type'],$package_ids,$countries_code,$exist_group,$sort_by,$pegging_countries_code,$condition['top_limit']);
        //output the string with a loop.
        foreach($exist_group as $list) {
            $method_name = 'set'.$list.'BodyString';
            $data_tmp = (!isset($data[$list]) || empty($data[$list])) ? array() : $data[$list];
            $output .= $this->{$method_name}($data_tmp,$conditions);
        }
        return $output;
    }

    //set the total summary list 
    private function setTotalSummaryBodyString($conditions) {
        if (empty($conditions)) return ErrorMessage::HAVE_NO_PARAMERTERS;
        $condition = array();
        $condition = $conditions['condition'];
        $sort_by = $conditions['sort'];
        $countries_code = array();
        $data = array();
        $total_summary = null;

        $content_type = $condition['content_type'];
        if (!empty($condition['country_code'])) {
            $country_arr = $condition['country_code'];
            $countries_code = AC::getInstance()->getRegionCountryCondtion($country_arr);
        }

        $data = $this->getTotalSummaryOfReport($condition['play_time'],$condition['category_path'],$content_type,$countries_code,$condition['age_group'],$condition['gender'],$condition['package_id'],$sort_by,$condition['top_limit']);
        $total_summary = $this->setParagraphTitle(AC::VIDEO_VIEWING_REPORT_TOTAL_SUMMARY);
        $total_summary.= (!empty($data['data'])) ? $this->setMainBodyListByNone($data,$sort_by,false) : $this->setMainBodyListHaveNone();

        return $total_summary;
    }

    //set the report list for gender and age group.
    private function setGenderAgeBodyString($data,$conditions) {
        $condition = array();
        $age_group_array = array();
        $gender_age_body = null;
        $countries_code = array();
        $package_ids = array();
        $condition = $conditions['condition'];
        $sort_by = $conditions['sort'];

        if (isset($data['video_ids']) && !empty($data['video_ids'])) {
            $video_ids = $data['video_ids'];
            unset($data['video_ids']);
            $data['video_info'] = $this->getVideoTitleByVideoIds($video_ids);
        }
        

        //Gender & Age
        if (!empty($condition['age_group']) || !empty($condition['gender'])) {
            $age_group_array_ = AC::getInstance()->getConfigSetting(AC::$age_list);
            foreach($age_group_array_ as $k=>$v) {
                if ($k<1) continue;
                $age_group_array[$k] = $v;
            }
            if (!empty($condition['country_code'])) {
                $country_arr = $condition['country_code'];
                $countries_code = AC::getInstance()->getRegionCountryCondtion($country_arr);
            }
            if ($condition['content_type']==2 && !empty($condition['package_id'])) {
                $package_ids = $condition['package_id'];
            }

            $gender_age_body =  $this->setParagraphTitle(AC::VIDEO_VIEWING_REPORT_GENDER_AGE_GROUP);
            $gender_age_body .= (!empty($data['data'])) ? $this->setMainBodyList($data,$condition['gender'],$condition['age_group'],$sort_by,$age_group_array) : $this->setMainBodyListHaveNone();
        }

        return $gender_age_body;
    }
    
    //get the report list for region & country.
    private function setRegionCountryBodyString($data,$conditions) {
        $condition = array();
        $condition = $conditions['condition'];
        $sort_by = $conditions['sort'];
        $region_country = null;

        if (isset($data['video_ids']) && !empty($data['video_ids'])) {
            $video_ids = $data['video_ids'];
            unset($data['video_ids']);
            $data['video_info'] = $this->getVideoTitleByVideoIds($video_ids);
        }
        
        //Region & Country
        if (isset($condition['country_code']) && !empty($condition['country_code'])) {
            $country_arr = $condition['country_code'];
            $tmp_country_code_list = AC::getInstance()->getRegionCountryCondtion($country_arr);
            $region_country = $this->setParagraphTitle(AC::VIDEO_VIEWING_REPORT_REGION_COUNTRY_GROUP);
            $region_country .= (!empty($data['data'])) ? $this->setMainBodyList_($data,array_keys($tmp_country_code_list),$tmp_country_code_list,$sort_by) : $this->setMainBodyListHaveNone();
        }
        
        return $region_country;
    }

    //get the report list for Subscription plan
    private function setSubscriptionPlanBodyString($data,$conditions) {
        $condition = array();
        $package_array = array();
        $condition = $conditions['condition'];
        $sort_by = $conditions['sort'];
        $subscription_body = null;

        if (isset($data['video_ids']) && !empty($data['video_ids'])) {
            $video_ids = $data['video_ids'];
            unset($data['video_ids']);
            $data['video_info'] = $this->getVideoTitleByVideoIds($video_ids);
        }

        //get output package list.
        $package_array_ = AC::getInstance()->getConfigSetting(AC::$video_plan_package);
        foreach($package_array_ as $k=>$v) {
            if ($k==0 && strtoupper($v)=='ALL') continue;
            $package_array[$k] = $v;
        }

        //Subscription Plan Group.
        if (!empty($condition['age_group']) && (!empty($condition['content_type']) || !empty($condition['package_id']))) {
            if ($condition['content_type']!=1 && !empty($condition['package_id'])) {
                $subscription_body = $this->setParagraphTitle(AC::VIDEO_VIEWING_REPORT_SUBSCRIPTION_PLAN);
                $subscription_body .= (!empty($data['data'])) ? $this->setMainBodyList($data,$condition['content_type'],$condition['package_id'],$sort_by,$package_array) : $this->setMainBodyListHaveNone();
            }
                
        }
        else if (!empty($condition['content_type']) && ($condition['content_type']==2 && !empty($condition['package_id']))) {
            $subscription_body = $this->setParagraphTitle(AC::VIDEO_VIEWING_REPORT_SUBSCRIPTION_PLAN);
            $subscription_body .= (!empty($data['data'])) ? $this->setMainBodyList($data,$condition['content_type'],$condition['package_id'],$sort_by,$package_array) : $this->setMainBodyListHaveNone();
        }

        return $subscription_body;
    }
    

    //set the show contents.**entrance.
    protected function __renderHead() {
        $body_string = '';
        $rand_code = rand(10000,99999);

        //parameters re-assignment.
        $conditions = $_GET;
        $conditions['country_code'] = $conditions['country'];
        $conditions = $this->getPageCondition($conditions);

        //get the header string.
        $head_string = $this->setHeadString($conditions['condition'],$conditions['sort'],$rand_code);

        //get the total summary.
        $body_string .= $this->setTotalSummaryBodyString($conditions);
        
        //get the body string.
        $body_string .= $this->setAllGroupBodyStringOptimization($conditions);

        //write a tmp file Export Tool.
        $export_html_string = $this->getOutPutBody($head_string['export'],$body_string);
        $write_result = AC::getInstance()->writeTempBodyToFile($rand_code,$export_html_string);

        //output.
        $this->contents =$this->getOutPutBody($head_string['view'],$body_string);
    }

}

?>
